import React, { useState, useEffect } from 'react';
import { Button, Input, Tag, Space, Popconfirm, message, Select, Form, Modal, Upload, Switch } from 'antd';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { 
  PlusOutlined, 
  SearchOutlined, 
  DeleteOutlined, 
  EditOutlined, 
  EyeOutlined,
  BookOutlined,
  TeamOutlined,
  GlobalOutlined,
  UserOutlined,
  CalendarOutlined,
  OrderedListOutlined,
  CheckCircleOutlined,
  StopOutlined
} from '@ant-design/icons';
import { FilterCard, TableCard } from '@/components/common';
import { ProblemSet } from '@/types/problemSet';
import { problemSetService } from '@/services/problemSetService';

const { Option } = Select;

interface ProblemSetListProps {
  isAdmin?: boolean;
  basePath?: string;
}

const ProblemSetList: React.FC<ProblemSetListProps> = ({ 
  isAdmin = false,
  basePath = '/problem' 
}) => {
  const navigate = useNavigate();
  const [searchParams, setSearchParams] = useSearchParams();
  
  // 从URL参数中获取初始状态
  const getInitialPage = () => {
    const page = searchParams.get('page');
    return page ? parseInt(page) : 1;
  };

  const getInitialKeyword = () => {
    return searchParams.get('keyword') || '';
  };

  const getInitialVisibility = () => {
    return searchParams.get('visibility') || 'all';
  };

  const [loading, setLoading] = useState(false);
  const [problemSets, setProblemSets] = useState<ProblemSet[]>([]);
  const [pagination, setPagination] = useState({
    current: getInitialPage(),
    pageSize: 10,
    total: 0,
  });
  const [searchKeyword, setSearchKeyword] = useState(getInitialKeyword());
  const [visibilityFilter, setVisibilityFilter] = useState(getInitialVisibility());

  // 更新URL参数的函数
  const updateURLParams = (page: number, keyword: string, visibility: string) => {
    const params = new URLSearchParams();
    if (page > 1) params.set('page', page.toString());
    if (keyword) params.set('keyword', keyword);
    if (visibility && visibility !== 'all') params.set('visibility', visibility);
    
    setSearchParams(params);
  };

  const fetchProblemSets = async (page = 1, keyword = '', visibility = visibilityFilter) => {
    try {
      setLoading(true);
      const params: any = {
        page,
        limit: pagination.pageSize,
      };
      
      if (keyword) {
        // 后端API可能使用不同的参数名，这里使用title进行搜索
        params.title = keyword;
      }
      
      // 管理端：传递实际的 visibility 值（包括 'all'）
      // 用户端：只传递非 'all' 的值，默认不传则后端返回公开题单
      if (isAdmin) {
        if (visibility) {
          params.visibility = visibility;
        }
      } else {
        if (visibility && visibility !== 'all') {
          params.visibility = visibility;
        }
      }

      const response = await problemSetService.getProblemSets(params);
      const data = response.data.data;
      
      setProblemSets(data.results);
      setPagination({
        ...pagination,
        current: page,
        total: data.count,
      });
      
      // 更新URL参数
      updateURLParams(page, keyword, visibility);
    } catch (error) {
      message.error('获取题单列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 初始化时从URL参数获取数据
  useEffect(() => {
    const initialPage = getInitialPage();
    const initialKeyword = getInitialKeyword();
    const initialVisibility = getInitialVisibility();
    fetchProblemSets(initialPage, initialKeyword, initialVisibility);
  }, []);



  const handleDelete = async (id: number) => {
    try {
      await problemSetService.deleteProblemSet(id);
      message.success('删除成功');
      fetchProblemSets(pagination.current, searchKeyword, visibilityFilter);
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handleToggleActive = async (id: number, currentActive: boolean) => {
    try {
      await problemSetService.updateProblemSet(id, { is_active: !currentActive });
      message.success(currentActive ? '已停用题单' : '已启用题单');
      fetchProblemSets(pagination.current, searchKeyword, visibilityFilter);
    } catch (error) {
      message.error('操作失败');
    }
  };

  const getColumns = () => {
    const baseColumns = [
      {
        title: <><BookOutlined /> 标题</>,
        dataIndex: 'title',
        render: (text: string, record: ProblemSet) => (
          <a 
            onClick={() => navigate(`${basePath}/problem-set/${record.id}`)}
            style={{ color: 'var(--primary-color)', cursor: 'pointer' }}
          >
            {text}
          </a>
        ),
      },
      {
        title: '描述',
        dataIndex: 'description',
        ellipsis: true,
        width: 200,
      },
      {
        title: '可见性',
        dataIndex: 'visibility',
        width: 100,
        render: (visibility: string) => (
          <Tag color={visibility === 'public' ? 'green' : 'blue'}>
            {visibility === 'public' ? <GlobalOutlined /> : <TeamOutlined />}
            {visibility === 'public' ? '公开' : '团队'}
          </Tag>
        ),
      },
      {
        title: '团队',
        dataIndex: 'team_name',
        width: 120,
        render: (teamName: string | null) => (
          teamName ? <Tag color="blue">{teamName}</Tag> : <span>-</span>
        ),
      },
      {
        title: '题目数量',
        dataIndex: 'problem_count',
        width: 100,
        render: (count: number) => (
          <Tag color="orange">{count} 题</Tag>
        ),
      },
      {
        title: '创建者',
        dataIndex: 'creator_name',
        width: 100,
        render: (name: string) => (
          <span>
            <UserOutlined /> {name}
          </span>
        ),
      },
      {
        title: '创建时间',
        dataIndex: 'created_time',
        width: 120,
        render: (time: string) => (
          <span>
            <CalendarOutlined /> {new Date(time).toLocaleDateString()}
          </span>
        ),
      },
      {
        title: '状态',
        dataIndex: 'is_active',
        width: 60,
        render: (isActive: boolean, record: ProblemSet) => (
          <Switch
            checked={isActive}
            onChange={() => handleToggleActive(record.id, isActive)}
            checkedChildren={<CheckCircleOutlined />}
            unCheckedChildren={<StopOutlined />}
            size="small"
          />
        ),
      },
    ];

    // 操作列
    const actionColumn = {
      title: '操作',
      key: 'action',
      width: isAdmin ? 250 : 120,
      render: (_: any, record: ProblemSet) => (
        <Space size="small">
          <Button 
            type="link" 
            size="small"
            icon={<EyeOutlined />} 
            onClick={() => navigate(`${basePath}/problem-set/${record.id}`)}
          >
            查看
          </Button>
          
          {isAdmin && (
            <>
              <Button 
                type="link" 
                size="small"
                icon={<EditOutlined />} 
                onClick={() => navigate(`${basePath}/problem-set/edit/${record.id}`)}
              >
                编辑
              </Button>
              <Popconfirm
                title="确定要删除这个题单吗？"
                onConfirm={() => handleDelete(record.id)}
                okText="确定"
                cancelText="取消"
              >
                <Button 
                  type="link" 
                  size="small"
                  danger 
                  icon={<DeleteOutlined />}
                >
                  删除
                </Button>
              </Popconfirm>
            </>
          )}
        </Space>
      ),
    };

    return [...baseColumns, actionColumn];
  };

  const [form] = Form.useForm();

  // 当URL参数变化时，更新表单的初始值
  useEffect(() => {
    form.setFieldsValue({
      keyword: searchKeyword,
      visibility: visibilityFilter,
    });
  }, [form, searchKeyword, visibilityFilter]);

  const handleFormFinish = (values: any) => {
    const newKeyword = values.keyword || '';
    const newVisibility = values.visibility || 'all';
    setSearchKeyword(newKeyword);
    setVisibilityFilter(newVisibility);
    fetchProblemSets(1, newKeyword, newVisibility);
  };

  const handleReset = () => {
    setSearchKeyword('');
    setVisibilityFilter('all');
    // 重置时清空URL参数
    setSearchParams({});
    fetchProblemSets(1, '', 'all');
  };

  return (
    <div>
      <FilterCard
        pageTitle="题单列表"
        titleIcon={<OrderedListOutlined />}
        form={form}
        onFinish={handleFormFinish}
        onReset={handleReset}
        extra={
          isAdmin ? (
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => navigate(`${basePath}/problem-set/create`)}
            >
              创建题单
            </Button>
          ) : null
        }
      >
        <Form.Item name="keyword" label="关键词" initialValue={searchKeyword}>
          <Input placeholder="搜索题单" style={{ width: 200 }} />
        </Form.Item>
        <Form.Item name="visibility" label="可见性" initialValue={visibilityFilter}>
          <Select style={{ width: 120 }}>
            <Option value="all">全部</Option>
            <Option value="public">公开</Option>
            <Option value="team">团队</Option>
          </Select>
        </Form.Item>
      </FilterCard>

      <TableCard
        tableProps={{
          columns: getColumns(),
          dataSource: problemSets,
          rowKey: 'id',
          pagination: {
            ...pagination,
            onChange: (page) => fetchProblemSets(page, searchKeyword, visibilityFilter),
            showSizeChanger: false,
          },
          loading: loading,
          size: 'small',
        }}
      />
    </div>
  );
};

export default ProblemSetList; 